package com.passer.simpletransfer.service.impl;

import com.passer.simpletransfer.config.SimpleTransferProperties;
import com.passer.simpletransfer.model.TransferFile;
import com.passer.simpletransfer.service.FileDownloadService;
import com.passer.toolbox.common.file.util.FileUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>FileDownloadService 实现类</p>
 * <p>创建时间：2023/2/2</p>
 *
 * @author hj
 */
@Slf4j
@Service
public class FileDownloadServiceImpl implements FileDownloadService {
    private final SimpleTransferProperties simpleTransferProperties;

    @Autowired
    public FileDownloadServiceImpl(SimpleTransferProperties simpleTransferProperties) {
        this.simpleTransferProperties = simpleTransferProperties;
    }

    @Override
    public List<TransferFile> getList() {
        File folder = new File(simpleTransferProperties.getSaveFolderPath());
        File[] files = folder.listFiles();
        List<TransferFile> transferFiles = new ArrayList<>();

        if (!folder.exists() || files == null || files.length < 1) {
            return transferFiles;
        }
        Pattern compile = Pattern.compile("^\\d+_(.*)$");
        for (File file : files) {
            String name = file.getName();
            Matcher matcher = compile.matcher(name);

            TransferFile transferFile = new TransferFile();
            transferFile.setMd5(name);
            transferFile.setName(matcher.find() ? matcher.group(1) : name);
            transferFile.setSize(file.length());
            transferFile.setSizeStr(FileUtils.fileSizeConvert(transferFile.getSize(), 2));
            transferFile.setDownloadUrl(simpleTransferProperties.getStaticPathPattern().replace("**", "") + transferFile.getMd5());
            transferFiles.add(transferFile);
        }
        return transferFiles;

    }

    @Override
    public void downloadFile(String code, HttpServletRequest request, HttpServletResponse response) {
        String saveFolderPath = simpleTransferProperties.getSaveFolderPath();
        File file = new File(saveFolderPath,  code);
        if (!file.exists()) {
            throw new RuntimeException("未找到文件");
        }
        // 读取文件到流中
        try (InputStream inputStream = new FileInputStream(file);
             ServletOutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件未找到", e);
        } catch (IOException e) {
            throw new RuntimeException("读取文件时发生错误", e);
        }

        // 设置响应头
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8) + "\"");
    }


    @Override
    public void deleteFile(String fileMd5) {
        File folder = new File(simpleTransferProperties.getSaveFolderPath(), fileMd5);
        if (folder.exists()) {
            FileUtils.deleteFolder(folder, true);
        }
    }
}
